/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.wgx.modules.sys.util;

import cn.wgx.commons.util.Exceptions;
import cn.wgx.commons.util.Servlets;
import cn.wgx.commons.util.SpringContextHolder;
import cn.wgx.commons.util.StringUtils;
import cn.wgx.modules.sys.entity.SysLog;
import cn.wgx.modules.sys.entity.SysUser;
import cn.wgx.modules.sys.services.SysLogService;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 日志工具类
 * @author ThinkGem
 * @version 2014-11-7
 */
public class LogUtil {
	
	public static final String CACHE_MENU_NAME_PATH_MAP = "menuNamePathMap";
	
	private static SysLogService sysLogService = SpringContextHolder.getBean(SysLogService.class);

	/**
	 * 保存日志
	 */
	public static void saveLog(HttpServletRequest request, String title){
		saveLog(request, null, null, title);
	}
	
	/**
	 * 保存日志
	 */
	public static void saveLog(HttpServletRequest request, Object handler, Exception ex, String title){
		SysUser user = UserUtil.getUser();
		if ((user != null && user.getUser_id() != null) || title != null){
			SysLog log = new SysLog();
			log.setTitle(title);
//			log.setType(ex == null ? SysLog.TYPE_ACCESS : SysLog.TYPE_EXCEPTION);
//			log.setType("test");
			log.setRemote_host(Servlets.getRemoteAddr(request));
			log.setUser_agent(request.getHeader("user-agent"));
			log.setRequest_uri(Servlets.getRequestUri());
			log.setMethod(request.getMethod());
			log.setCreateUserId(user != null ? user.getUser_id() : 0);
//			log.setParams(request.getQueryString());
			Map map = request.getParameterMap();
//			request.getQueryString();
			if(map != null){
                StringBuilder params = new StringBuilder();
                for (Map.Entry<String, String[]> param : ((Map<String, String[]>)map).entrySet()){
                    params.append(("".equals(params.toString()) ? "" : "&") + param.getKey() + "=");
                    String paramValue = (param.getValue() != null && param.getValue().length > 0 ? param.getValue()[0] : "");
                    params.append(StringUtils.abbr(StringUtils.endsWithIgnoreCase(param.getKey(), "password") ? "" : paramValue, 100));
                }
                log.setParams(params.toString());
            }
			// 异步保存日志
			new SaveLogThread(log, handler, ex).start();
		}
	}

	/**
	 * 保存日志线程
	 */
	public static class SaveLogThread extends Thread{
		
		private SysLog log;
		private Object handler;
		private Exception ex;
		
		public SaveLogThread(SysLog log, Object handler, Exception ex){
			super(SaveLogThread.class.getSimpleName());
			this.log = log;
			this.handler = handler;
			this.ex = ex;
		}
		
		@Override
		public void run() {
			// 获取日志标题
			if (StringUtils.isBlank(log.getTitle())){
				log.setTitle(PermissionUtil.getPerNameByUri(log.getRequest_uri(), log.getMethod()));
			}
			// 如果有异常，设置异常信息
			log.setException(Exceptions.getStackTraceAsString(ex));
			// 如果无标题并无异常日志，则不保存信息
			if (StringUtils.isBlank(log.getTitle())
					&& StringUtils.isBlank(log.getException())){
				return;
			}
			// 保存日志信息
			//log.preInsert();
			sysLogService.insertOne(log);
		}
	}

	/**
	 * 获取菜单名称路径（如：系统设置-机构用户-用户管理-编辑）
	 */
//	public static String getMenuNamePath(String requestUri, String permission){
//		String href = StringUtils.substringAfter(requestUri, Global.getAdminPath());
//		@SuppressWarnings("unchecked")
//		Map<String, String> menuMap = (Map<String, String>)CacheUtils.get(CACHE_MENU_NAME_PATH_MAP);
//		if (menuMap == null){
//			menuMap = Maps.newHashMap();
//			List<Menu> menuList = menuDao.findAllList(new Menu());
//			for (Menu menu : menuList){
//				// 获取菜单名称路径（如：系统设置-机构用户-用户管理-编辑）
//				String namePath = "";
//				if (menu.getParentIds() != null){
//					List<String> namePathList = Lists.newArrayList();
//					for (String id : StringUtils.split(menu.getParentIds(), ",")){
//						if (Menu.getRootId().equals(id)){
//							continue; // 过滤跟节点
//						}
//						for (Menu m : menuList){
//							if (m.getId().equals(id)){
//								namePathList.add(m.getName());
//								break;
//							}
//						}
//					}
//					namePathList.add(menu.getName());
//					namePath = StringUtils.join(namePathList, "-");
//				}
//				// 设置菜单名称路径
//				if (StringUtils.isNotBlank(menu.getHref())){
//					menuMap.put(menu.getHref(), namePath);
//				}else if (StringUtils.isNotBlank(menu.getPermission())){
//					for (String p : StringUtils.split(menu.getPermission())){
//						menuMap.put(p, namePath);
//					}
//				}
//
//			}
//			CacheUtils.put(CACHE_MENU_NAME_PATH_MAP, menuMap);
//		}
//		String menuNamePath = menuMap.get(href);
//		if (menuNamePath == null){
//			for (String p : StringUtils.split(permission)){
//				menuNamePath = menuMap.get(p);
//				if (StringUtils.isNotBlank(menuNamePath)){
//					break;
//				}
//			}
//			if (menuNamePath == null){
//				return "";
//			}
//		}
//		return menuNamePath;
//	}

}
